package org.jtzc.springaiembedding.util;

/**
 * @author wu chuang
 * @description
 */
public class Util {
    // 计算向量点积
    public static float dotProduct(float[] vec1, float[] vec2) {
        if (vec1.length != vec2.length) {
            throw new IllegalArgumentException("向量维度必须相同");
        }
        float sum = 0.0f;
        for (int i = 0; i < vec1.length; i++) {
            sum += vec1[i] * vec2[i];
        }
        return sum;
    }

    public static float norm(float[] vector) {
        float sum = 0.0f;
        for (float v : vector) {
            sum += Math.pow(v, 2);
        }
        return (float)Math.sqrt(sum);
    }

    public static float cosineSimilarity(float[] vec1, float[] vec2) {
        float dot = dotProduct(vec1, vec2);
        float norm1 = norm(vec1);
        float norm2 = norm(vec2);

        if (norm1 == 0 || norm2 == 0) {
            return 0f;
        }
        return dot / (norm1 * norm2);
    }
}
